package com.ash.android_adk_demo

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.hc.schedule.model.Subscription
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import com.ash.base.bean.HcResult
import com.ash.base.logd
import com.ash.base.loge
import com.ash.base.repository.BaseRepository
import com.ash.android_adk_demo.DaysAdapter
import com.ash.android_adk_demo.OnTaskClickListener
import com.hc.player.common.IPlayerListener
import com.hc.player.common.PlayerEventBus
import com.hc.player.player.ASMRPlayer
import com.hc.schedule.model.AudioTask
import com.hc.schedule.model.Schedule
import com.hc.schedule.model.TaskStatus
import com.hc.schedule.service.SubscriptionService
import com.hc.schedule.service.TaskService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@RequiresApi(Build.VERSION_CODES.O)
class ScheduleDetailActivity : ComponentActivity(),
    OnTaskClickListener {

    companion object {
        const val TAG = "ScheduleDetailActivity"
        const val EXTRA_SCHEDULE_DATA = "extra_schedulescheduleJson_data"
    }

    private lateinit var daysAdapter: DaysAdapter
    private var subscription: Subscription? = null
    private var isSubscribed = false
    // 初始化播放器
    val player: ASMRPlayer by lazy { ASMRPlayer(applicationContext) }
    var  scheduleJson = ""

    var currDay = 0

    var currTask: AudioTask? = null

    lateinit var tv_time:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_schedule_detail)

        tv_time = findViewById<TextView>(R.id.tv_schedule_detail_time)
        findViewById<Button>(R.id.butt_schedule_detail_audio).setOnClickListener {
            player.stop()
        }

        // 获取传递的数据
        scheduleJson = intent.getStringExtra(
            EXTRA_SCHEDULE_DATA
        )?:""
        fetchDetail(scheduleJson)
        PlayerEventBus.instance.addLisenter(object : IPlayerListener{
            override fun onCacheAllDone(exception: java.lang.Exception?) {
            }

            override fun onCachePreDownloadDone() {
            }

            override fun onCacheError(e: java.lang.Exception) {
            }

            override fun onClearCache() {
            }

            override fun onTick(tick: Long) {
                tv_time.text = "播放时长：$tick s"
                if (tick >= 300 && (tick % 60).toInt() == 0){
                    currTask?.let{
                        GlobalScope.launch {
                            TaskService().updateTask(it,tick.toInt(),this@ScheduleDetailActivity)
                        }
                    }
                }
            }

            override fun onFinished() {
                "播放完成".logd()
                fetchDetail(scheduleJson)
            }

            override fun onPlay() {
            }

            override fun onPause() {
            }

            override fun onPlayError(e: java.lang.Exception) {
            }

        })

    }

    fun fetchDetail(scheduleJson:String){
        if (scheduleJson.isNotEmpty()) {
            try {
                val schedule = Gson().fromJson(scheduleJson, Schedule::class.java)
                GlobalScope.launch {
                    var userId = BaseRepository(this@ScheduleDetailActivity).getUserUUID() ?: ""
                    var subscritionService = SubscriptionService()
                    var result = subscritionService.fetchSubscriptionDetail(
                        userId,
                        schedule,
                        this@ScheduleDetailActivity
                    )
                    withContext(Dispatchers.Main) {
                        if (result is HcResult.Success) {
                            "订阅详情加载成功:${Gson().toJson(result.data)} ".logd()
                            updateSubscribe(result.data)
                        } else {
                            "订阅详情失败".loge()
                                showToast("订阅详情加载失败")

                        }
                    }
                }

            } catch (e: Exception) {
               "Error parsing subscription data: ${e.message}".loge()
            }
        }
    }

    fun updateSubscribe(subscription: Subscription){
        this.subscription = subscription
        displaySubscriptionDetails()
    }

    private fun handSubscribe(){
        var subscriptionServicer = SubscriptionService()

        var userId = BaseRepository(this@ScheduleDetailActivity).getUserUUID()

        GlobalScope.launch {
            var result:HcResult<Subscription>? = null
            subscription?.let {
                if (isSubscribed) {
                    try {
                        subscriptionServicer.unsubscribe(
                            it.schedule,
                            this@ScheduleDetailActivity
                        )
                            showToast("取消订阅成功")

                        finish()
                    }catch (e:Exception){
                            showToast("取消订阅失败")

                    }
                } else {
                    result = subscriptionServicer.subscribe(
                        userId?:"",
                        it.schedule,
                        this@ScheduleDetailActivity
                    )
                }
            }
            result?.let{
                if (it is HcResult.Success) {
                    updateSubscribe(it.data)
                } else if(it is HcResult.Error){
                        showToast("订阅失败 ${it.mess}")

                }
            }
        }

    }

    private fun displaySubscriptionDetails() {
        subscription?.let { sub ->
            runOnUiThread {
                // 显示计划信息
                isSubscribed = sub.schedule.isSubscribed
                val tvPlanName = findViewById<TextView>(R.id.tv_plan_name)
                val tvPlanAdd = findViewById<TextView>(R.id.tv_plan_add)
                val tvPlanProgress = findViewById<TextView>(R.id.tv_plan_progress)

                tvPlanName.text = "计划名称: ${sub.schedule.name}"

                tvPlanAdd.text = if (isSubscribed) "已订阅(点击取消订阅)" else "未订阅(点击订阅)"

                if (isSubscribed == false) {
                    tvPlanAdd.setBackgroundColor(Color.RED)
                    tvPlanAdd.setOnClickListener {
                        "订阅".logd()
                        handSubscribe()
                    }
                } else {
                    tvPlanAdd.setBackgroundColor(Color.GREEN)
                    tvPlanAdd.setOnClickListener {
                        "取消订阅".logd()
                        handSubscribe()
                    }
                }

                currDay = sub.schedule.currentDay ?: 0
                val totalDays = sub.dayList.size
                tvPlanProgress.text = "进度: 第${currDay}天 / 共${totalDays}天"

                // 设置天数列表
                setupDaysRecyclerView(sub)
            }
        }
    }

    private fun setupDaysRecyclerView(subscription: Subscription) {
        daysAdapter = DaysAdapter(subscription.dayList, this,currDay)
        val rvDays = findViewById<RecyclerView>(R.id.rv_days)
        rvDays.apply {
            layoutManager = LinearLayoutManager(this@ScheduleDetailActivity)
            adapter = daysAdapter
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        player.stop()
    }

    
    override fun onTaskClick(task: AudioTask) {
        currTask = task
        if (task.status == TaskStatus.NotFinished) {
            // 获取用户ID
            val userId = BaseRepository(this).getUserUUID() ?: ""
            
            // 显示加载中提示
                showToast("正在加载音频任务...")

            
            GlobalScope.launch {
                try {
                    // 获取音频方案
                    val taskService = TaskService()
                    "${Gson().toJson(task)}".logd("task:")
                    val result = taskService.fetchAudioSolution(userId, task, this@ScheduleDetailActivity)
                    
                    withContext(Dispatchers.Main) {
                        if (result is HcResult.Success) {
                           player.prepare(result.data,(task.duration/60).toLong(),true)
                        } else if (result is HcResult.Error) {
                                showToast("获取音频方案失败: ${result.mess}")

                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                            showToast("播放失败: ${e.message}")
                    }
                }
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}